# -*- coding: utf-8 -*-
##############################################################
#             Copyright (C), 2009-2013, ali
#
# FileName:   SDTReport.py
# Author:     yixun.zengyx
# Version:    0.1
#
# Description:
#   Client
#
#
# Function List:
#
#
# History:
#     <Author/Maintainer>      <Date>      <Modification>
#       yixun.zengyx        2013/04/18    Create this file
#############################################################
import sys
import json
import urllib 
from httplib2 import Http
import ShareFunc as SF

class CharSetParam:
    @staticmethod
    def encode(param,charset="utf-8"):
#         if param==None:
#             param = {}
#         same_encode = False
#         if sys.stdin.encoding.lower()==charset.lower():
#             same_encode = True
#         keys = param.keys()
#         values = map(param.get, keys)
#         v = len(values)
#         for i in range(0,v):
#             if type(values[i]) is str:
#                 if same_encode:
#                     values[i] = values[i]
#                 else:
#                     values[i] = values[i].decode(sys.stdin.encoding).encode(charset)
#             if type(values[i]) is tuple:
#                 values[i] = list(values[i])
#             if type(values[i]) is list:
#                 vn = len(values[i])
#                 for j in range(0,vn):
#                     if type(values[i][j]) is str:
#                         if same_encode:
#                             values[i][j] = values[i][j]
#                         else:
#                             values[i][j] = values[i][j].decode(sys.stdin.encoding).encode(charset)
#                 values[i] = tuple(values[i])
#         n = len(keys)
#         for i in range(0, n):
#             if type(keys[i]) is str:
#                 if same_encode:
#                     keys[i] = keys[i]
#                 else:
#                     keys[i] = keys[i].decode(sys.stdin.encoding).encode(charset)
#         params = {}
#         for i in range(0,n):
#             params[keys[i]] = values[i]
        urlparams = json.dumps(param,encoding=charset)
        return urlparams

class SessionManage:
    session = {}

class RequestClient:
    def __init__(self):
        self.__domain="127.0.0.1"
        self.__timeout=30
        
    def GetTimeout(self):
        return self.__timeout
        
class HttpRequestClient(RequestClient):
    def __init__(self,timeout=60,cache='./cache'):
        self.__timeout=timeout
        self.client=Http(cache,self.__timeout)
#         self.client.follow_redirects = False
        
    def SetDomain(self,domain):
        if type(domain) is str:
            self.__domain = domain
            
    def GetDomain(self):
        return self.__domain
    
    
    def Send(self,path="",param={},username=None,method="GET",headers=None,charset="utf-8",contentType="application/x-www-form-urlencoded"):
        url = self.__domain+path
        if headers==None:
            headers={'Content-Type': contentType,"Cache-Control":"no-cache","Connection":"Keep-Alive"}
        if username<>None:
            if SessionManage.session.has_key(username):
                if SessionManage.session[username].has_key('set-cookie'):
                    headers['Cookie'] = SessionManage.session[username]['set-cookie']
            else:
                SessionManage.session[username] = {}
        print "headers:%s"%(str(headers))
        print "=====================session=========================="
        print SessionManage.session
        print "=====================session end======================"
        if param==None:
            param = {}
        same_encode = False
        if sys.stdin.encoding.lower()==charset.lower():
            same_encode = True
        if contentType=="application/x-www-form-urlencoded":
            keys = param.keys()
            values = map(param.get, keys)
            v = len(values)
            for i in range(0,v):
                if type(values[i]) is str:
                    if same_encode:
                        values[i] = values[i]
                    else:
                        values[i] = values[i].decode(sys.stdin.encoding).encode(charset)
                if type(values[i]) is tuple:
                    values[i] = list(values[i])
                if type(values[i]) is list:
                    vn = len(values[i])
                    for j in range(0,vn):
                        if type(values[i][j]) is str:
                            if same_encode:
                                values[i][j] = values[i][j]
                            else:
                                values[i][j] = values[i][j].decode(sys.stdin.encoding).encode(charset)
                    values[i] = tuple(values[i])
            n = len(keys)
            for i in range(0, n):
                if type(keys[i]) is str:
                    if same_encode:
                        keys[i] = keys[i]
                    else:
                        keys[i] = keys[i].decode(sys.stdin.encoding).encode(charset)
            params = {}
            for i in range(0,n):
                params[keys[i]] = values[i]
            urlparams = urllib.urlencode(params,1)
        elif (contentType=="application/json;charset=%s"%(charset)) or (contentType=="application/json"):
            if type(param) is not dict:
                urlparams = param
            else:
                urlparams = json.dumps(param,encoding=charset)
        if urlparams<>"":
            print "SDTest Url:%s?%s"%(url,urlparams)
        else:
            print "SDTest Url:%s"%(url)
        resp,content = self.client.request(url,method,urlparams,headers)
        if username<>None:
            if SessionManage.session.has_key(username):
                print username
                if resp.has_key("set-cookie"):
                    SessionManage.session[username]['set-cookie']=resp["set-cookie"]
#         content = str(content)
        if not same_encode:
            content = content.decode(charset).encode(sys.stdin.encoding)
            content = SF.ShareFunc.replaceXmlEncoding(content, sys.stdin.encoding)
        return resp,content
        
if __name__ == '__main__':
    req = SessionManage.session
    